//index.js
//获取应用实例
const app = getApp()

Page({
    data: {
        motto: 'Hello World',
		productData: {},
		curProductTitle: '',
		productBaseUrl: '',
		productId: '',
    },
    onLoad: function (options) {
		this.setData({
			productBaseUrl: app.globalData.productBaseUrl
		});
        var that = this;
        wx.request({
            url: 'http://192.168.1.199:3389/product/' + options.id,
            success: function (res) {
				var productName = res.data.product_name;
				wx.setNavigationBarTitle({
					title: productName ? productName : 'Product'
				});
                that.setData({
					productData: res.data,
					productId: options.id
                })
            }
        })
		console.log(this.data)
    },
	onHide: function() {
		console.log('onHide')
    },

	onLaunch: function () {
        console.log('onlaunch')
	},
	onShow: function() {
    },

	onUnlaunch: function() {
		console.log('onUnlaunch')
    },

	userInfoReadyCallback: function() {
		console.log('userInfoReadyCallback')
    },
	addToCart: function (e) {
		let curProduct = e.currentTarget.dataset.productInfo;
		let cartObj = {};
		wx.getStorage({
			key: 'cartList',
			success: function(res) {
				cartObj = res.data
				console.log('getstorage', cartObj)
				let product = cartObj[curProduct.product_id] || {};
				if(cartObj && cartObj[curProduct.product_id]){
					cartObj[curProduct.product_id].num ++ ;
				} else {
					cartObj[curProduct.product_id] = {
						id: curProduct.product_id,
						num: 1,
						name: curProduct.product_name,
						image: curProduct.product_image,
						price: curProduct.price
					}
				}
				app.globalData.cartList = {...cartObj};
				wx.setStorage({
					key:"cartList",
					data: cartObj
				})

				wx.switchTab({
					url: "../cart/index"
				});
			},
			fail: function (res) {
				console.log('product fail', res)
				cartObj[curProduct.product_id] = {
					id: curProduct.product_id,
					num: 1,
					name: curProduct.product_name,
					image: curProduct.product_image,
					price: curProduct.price
				}
				app.globalData.cartList = {...cartObj};
				wx.setStorage({
					key:"cartList",
					data: cartObj
				})

				wx.switchTab({
					url: "../cart/index"
				});
			}
		});
	},
	onShareAppMessage: function (res) {
		if (res.from === 'button') {
			// 来自页面内转发按钮
			console.log(res.target)
		}
		return {
			title: '转发',
			path: '/page/product/index?id=' +  this.data.productId,
			success: function(res) {
				// 转发成功
				console.log('转发成功', res)
			},
			fail: function(res) {
				// 转发失败
				console.log('转发失败', res)
			}
		}
	}
})
